package com.aruio.controller;

import com.arui.Result;
import com.arui.exception.ServiceException;
import com.aruio.annotation.SwitchSource;
import com.aruio.dto.PandaExcelQueryDTO;
import com.aruio.dto.PandaDTO;
import com.aruio.service.PandaService;
import com.aruio.vo.PandaImportVO;
import com.aruio.vo.PandaVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Description panda控制器
 * @Date 2024/9/4 14:52
 * @Created by 10574
 */
@RestController
@RequestMapping("panda")
@RequiredArgsConstructor
@Slf4j
public class PandaController {
    private final PandaService pandaService;

    @PostMapping("import/v1")
    public Result<Object> importExcelV1(MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new ServiceException("上传的文件不能为空!");
        }
        pandaService.importExcelV1(file);
        return Result.status(true);
    }

    @PostMapping("export/v1")
    public void exportExcelV1(@RequestBody PandaExcelQueryDTO pandaExcelQueryDTO, HttpServletResponse response) {
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start("exportPandaExcelV1");
        log.debug("pandaExcelQueryDTO:{}", pandaExcelQueryDTO);
        pandaService.exportByCondition(pandaExcelQueryDTO, response);
        stopWatch.stop();
        log.info("-----------TotalTimeMillis:{}-----------", stopWatch.getTotalTimeMillis());
    }

    @PostMapping("import/v2")
    public Result<PandaImportVO<?>> importExcelV2(MultipartFile file) {
        if (Objects.isNull(file)) {
            throw new ServiceException("上传的文件不能为空!");
        }
        return Result.data(pandaService.importExcelV2(file));
    }

    /**
     * 多线程优化导出所有数据
     */
    @PostMapping("export/v2")
    public Result<Object> exportExcelV2(HttpServletResponse response) {
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start("exportPandaExcelV2");
        final Integer taskId = pandaService.exportPandaExcelV2(response);
        stopWatch.stop();
        log.info("-----------TotalTimeMillis:{}-----------", stopWatch.getTotalTimeMillis());
        return Result.status(true);
    }

    @GetMapping("queryPandas")
    @SwitchSource("master")
    public Result<PageInfo<PandaVO>> queryPandas(final PandaDTO pandaDTO) {
        return Result.data(PageHelper.startPage(pandaDTO.getPageNum(), pandaDTO.getPageSize()).doSelectPageInfo(() -> pandaService.queryPandas(pandaDTO)));
    }

    @GetMapping("queryPanda")
    @SwitchSource("master")
    public Result<PandaVO> queryPanda(final PandaDTO pandaDTO) {
        return Result.data(pandaService.queryPanda(pandaDTO));
    }
}
